package com.qitianyong.selfclass;

import android.support.annotation.NonNull;

import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.data.DataFetcher;
import com.gkusbsdk.SZUSBFile;
import com.gkusbsdk.SZUSBIFrame;

import java.nio.ByteBuffer;
import java.util.Arrays;

import de.greenrobot.event.EventBus;

/**
 * Created by gy on 2018/3/22.
 */

public class UvcDataFetcher  implements DataFetcher<ByteBuffer> {

    private final SZUSBFile model;
    private byte[] bytes;
    private DataCallback<? super ByteBuffer> callback;

    public UvcDataFetcher(SZUSBFile model) {
        this.model = model;
    }

    @Override
    public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super ByteBuffer> callback) {
        this.callback = callback;
        EventBus.getDefault().register(this);
        GKDevice.getInstance().sendCommand( CONSTANT.COMMAND.CMD_GET_PHOTO, model);
    }
    public void onEvent(Message2EventBus message) {

        switch (message.__what) {


            case BUS_MESSAGE.BUS_SMALL_PHOTO_ERR:
                //因跨设备传输，有一定的不可靠性，建议添加获取失败重试策略。
                SZUSBIFrame object1 = (SZUSBIFrame) message.object;
                if(!Arrays.equals(Arrays.copyOf(object1.__name,object1.__name.length-1),model.__name)){
                    return;
                }
                callback.onLoadFailed(new RuntimeException("获取失败"));
                EventBus.getDefault().unregister(this);
            break;
            case BUS_MESSAGE.BUS_SMALL_PHOTO: {
                SZUSBIFrame object = (SZUSBIFrame) message.object;
                if(!Arrays.equals(Arrays.copyOf(object.__name,object.__name.length-1),model.__name)){
                    return;
                }
                bytes = object.__iFrame;

                if (bytes==null||bytes.length==0) {
                    callback.onLoadFailed(new RuntimeException("获取失败"));
                } else {
                    callback.onDataReady(ByteBuffer.wrap(bytes));
                }
                EventBus.getDefault().unregister(this);  break;
            }

            default:
                break;
        }
    }

    @Override
    public void cleanup() {

    }

    @Override
    public void cancel() {

    }

    @NonNull
    @Override
    public Class<ByteBuffer> getDataClass() {
        return ByteBuffer.class;
    }

    @NonNull
    @Override
    public DataSource getDataSource() {
        return DataSource.REMOTE;
    }
}
